package net.zigin.nhi.waste.view.print;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gyf.immersionbar.ImmersionBar;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.bean.PrintMsgBean;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.view.widget.OutOrderPrintDialog;
import net.zigin.nhi.waste.view.widget.PrintDialog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import Printer.PrintHelper;
import io.paperdb.Paper;
import io.reactivex.Observable;

/**
 * 出库单详情打印界面
 */
public class OutOrderDetailActivity extends AppCompatActivity {

    private TextView mCarNumber;
    private TextView mName;
    private TextView mPhone;
    private WebView mWebView;
    private TextView mTotal;
    private TextView mOuter;
    private Button mBtnPrint;

    private PrintHelper printHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        initView();

        printHelper = new PrintHelper();
        printHelper.Open(OutOrderDetailActivity.this);
    }

    private void initView() {
        ImmersionBar.with(this).init();
        mCarNumber = findViewById(R.id.car_number);
        mName = findViewById(R.id.name);
        mPhone = findViewById(R.id.phone);
        mWebView = findViewById(R.id.web_view);
        mTotal = findViewById(R.id.total);
        mOuter = findViewById(R.id.outer);
        mBtnPrint = findViewById(R.id.btn_print);
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onResume() {
        super.onResume();

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new PrintObject(), "connect");
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setDisplayZoomControls(false);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.loadUrl("file:///android_asset/output.html");

        String realName = Paper.book().read(Constants.REALNAME);
        if (StringUtil.isNotEmpty(realName)) {
            mOuter.setText(realName);
        }

        mBtnPrint.setOnClickListener(v -> {
            OutOrderPrintDialog dialog = new OutOrderPrintDialog(this, OutOrderDetailActivity.this, mWebView);
            dialog.show();
        });
    }

    /**
     * 获取出库单详情
     */
    private void getWasteOutInfo() {
        Intent intent = getIntent();
        String wasteOutId = intent.getStringExtra("wasteOutId");
        String receiver = intent.getStringExtra("receiver");
        String mobile = intent.getStringExtra("mobile");
        String carCode = intent.getStringExtra("carCode");
        String ckCode = intent.getStringExtra("ckCode");
        String realWeight = intent.getStringExtra("realWeight");
        mCarNumber.setText(carCode);
        mName.setText(receiver);
        mPhone.setText(mobile);
        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                .getWasteOutInfo(Paper.book().read(Constants.TOKEN), wasteOutId);
        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
            @SuppressLint("DefaultLocale")
            @Override
            protected void success(String data) {
                if (StringUtil.isNotEmpty(data)) {
                    Log.i("出库单详情", data);
                    List<PrintMsgBean> printMsgList = JSONArray.parseArray(data, PrintMsgBean.class);
                    mTotal.setText(realWeight);
                    //给webview传递数据
                    Map<String, Object> jsonData = new HashMap<>();
                    jsonData.put("ckCode", ckCode);
                    jsonData.put("dataList", printMsgList);
                    String json = JSONObject.toJSONString(jsonData);
                    Log.i("printObject", json);
                    String call = "javascript:getDetail('" + json + "')";
                    mWebView.loadUrl(call);
                }
            }
        });
    }

    class PrintObject {
        @JavascriptInterface
        public void print(final int x, final int y, final int width, final int height) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Picture pic = mWebView.capturePicture();
                        int nw = pic.getWidth();
                        int nh = pic.getHeight();
                        Bitmap bitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_4444);
                        Canvas can = new Canvas(bitmap);
                        pic.draw(can);

                        int newWidth = nw;
                        int newHeight = nh;
                        if (nw > 400) {
                            float rate = 380 * 1.0f / nw * 1.0f;
                            newWidth = 380;
                            newHeight = (int) (nh * rate);
                        }
                        bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
                        Bitmap newBitmap = Bitmap.createBitmap(bitmap, x, y, width, height);
                        printHelper.PrintBitmap(newBitmap);

                        printHelper.printBlankLine(40);
                    } catch (Exception | Error e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        @JavascriptInterface
        public void doFeed() {
            printHelper.Step((byte) 0x5f);
        }
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);// 当打开新链接时，使用当前的 WebView，不会使用系统其他浏览器
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //在这里执行你想调用的js函数
            getWasteOutInfo();
        }
    }
}